from Goldenberry.optimization.ga.GbSolutionRepMgr.Encoder import Encoder
import numpy as np

class DirectBinaryMapping(Encoder):
    phenotype = np.array([])
    """The phenotype is the same thet the genotype, not encoding required."""
    def encode_phenotype(self, binary):
        return binary

    def decode_genotype(self, binary):
        return binary

class GrayCodeMapping(Encoder):
    genotype = np.array([])
    phenotype = np.array([])

    """Encode a binary phenotype to a gray code genotype."""
    def encode_phenotype(self, binary):
        """converts a given binary number to is gray code"""
        gray = ""
        i = -1
        while( len(binary) > -i ):
            gray = `binary[i - 1] ^ binary[i]` + gray
            i -= 1
        gray = str(binary[0]) + gray
        gray_num= []
        for x in range(len(gray)):
            gray_num.append(int(gray[x]))
        self.genotype = np.array(gray_num)
        return self.genotype

    """Decode a gray code binary genotype to a binary phenotype."""
    def decode_genotype(self, bits):
        """converts a given gray code to its binary number"""
        b = [bits[0]]
        for nextb in bits[1:]: b.append(b[-1] ^ nextb)
        self.phenotype = np.array(b);
        return self.phenotype

  
